<template>
  <!-- 发表文章弹窗 -->
  <!-- 这里的visible不能加.sync -->
  <!-- @close="addDialogClose" 用@close会把发布文章关闭时也弹出$confirm弹窗，不符合需求 -->
  <!-- before-close 仅当用户通过点击关闭图标或遮罩关闭 Dialog 时起效。 -->
  <el-dialog
    class="addDialog"
    title="发表文章"
    :modal="false"
    :fullscreen="true"
    :visible="addDialogVisible"
    :before-close="addDialogClose"
  >
    <el-form :model="addForm" :rules="rules" ref="addForm">
      <!-- 文章标题 -->
      <el-form-item label="文章标题" :label-width="formLabelWidth" prop="title">
        <el-input
          v-model="addForm.title"
          autocomplete="off"
          maxlength="30"
          placeholder="请输入标题"
          @blur="addForm.title = addForm.title.replace(/(^\s*)|(\s*$)/g, '')"
        ></el-input>
      </el-form-item>
      <!-- 文章分类 -->
      <el-form-item
        label="文章分类"
        :label-width="formLabelWidth"
        prop="cate_id"
      >
        <!-- 父传子 artCateTable -->
        <el-select
          v-model="addForm.cate_id"
          placeholder="请选择分类"
          style="width: 100%"
        >
          <el-option
            v-for="item in cateTable"
            :key="item.id"
            :label="item.cate_name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 文章内容 -->
      <el-form-item
        label="文章内容"
        :label-width="formLabelWidth"
        prop="content"
      >
        <div class="local-quill-editor">
          <!-- @blur="onEditorBlur" -->
          <!-- @change="onEditorChange" -->
          <quill-editor
            ref="myLQuillEditor"
            v-model="addForm.content"
            :options="editorOption"
            class="editor"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <!-- 文章封面 -->
      <el-form-item
        label="文章封面"
        :label-width="formLabelWidth"
        prop="cover_img"
      >
        <!-- :on-success="handleAvatarSuccess" -->
        <el-upload
          class="avatar-uploader"
          ref="upload"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="httpRequest"
          accept=".jpg,.jpeg,.png,.gif,.webp,.svg"
        >
          <div class="avatar-wrapper">
            <img v-if="coverUrl" :src="coverUrl" class="avatar" />
            <img v-else src="@/assets/img/cover.040f5a70.jpg" class="avatar" />
            <div class="bottom">
              <el-button slot="trigger" size="medium" type="text"
                >+ 选择封面</el-button
              >
            </div>
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="addSubmit('已发布')">发布</el-button>
      <el-button type="info" @click="addSubmit('草稿')">存为草稿</el-button>
    </div>
  </el-dialog>
</template>

<script>
// 引入样式和quillEditor
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
import { addArticleApi } from "@/api/article";
export default {
  name: "AddArticleDialog",
  components: { quillEditor },
  props: ["addDialogVisible", "cateTable"],
  data() {
    // 工具栏配置项
    const toolbarOptions = [
      // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
      ["bold", "italic", "underline", "strike"],
      // 引用  代码块-----['blockquote', 'code-block']
      ["blockquote", "code-block"],
      // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
      [{ header: 1 }, { header: 2 }],
      // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
      [{ list: "ordered" }, { list: "bullet" }],
      // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
      [{ script: "sub" }, { script: "super" }],
      // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
      [{ indent: "-1" }, { indent: "+1" }],
      // 文本方向-----[{'direction': 'rtl'}]
      [{ direction: "rtl" }],
      // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
      [{ size: ["small", false, "large", "huge"] }],
      // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
      [{ header: [1, 2, 3, 4, 5, 6, false] }],
      // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
      [{ color: [] }, { background: [] }],
      // 字体种类-----[{ font: [] }]
      [{ font: [] }],
      // 对齐方式-----[{ align: [] }]
      [{ align: [] }],
      // 清除文本格式-----['clean']
      ["clean"],
      // 链接、图片、视频-----['link', 'image', 'video']
      ["link", "image", "video"],
    ];

    return {
      formLabelWidth: "100px",
      addForm: {
        title: "", // 是	string	文章标题	1-30 个字符
        cate_id: "", // 是	int	所属分类 Id	整数，最小值为 1
        content: "", // 是	string	文章内容	非空的字符串
        state: "", // 是	string	文章的发布状态	可选值为：已发布、草稿
        cover_img: "", // 是	blob二进制	文章封面	只能是图片文件
      },
      coverUrl: "", // 图片src
      form: "",
      // coverImgFile: "", // 展示的图片格式
      editorOption: {
        modules: {
          toolbar: toolbarOptions,
        },
        theme: "snow",
        // placeholder: "请输入正文",
        placeholder: "Insert text here...",
      },
      rules: {
        title: [
          {
            required: true,
            message: "文章标题不能为空",
            trigger: "change",
          },
          {
            min: 1,
            max: 30,
            message: "文章标题必须是1-30位的字符",
            trigger: "blur",
          },
        ],
        cate_id: [
          { required: true, message: "文章分类不能为空", trigger: "change" },
        ],
        content: [],
        cover_img: [],
      },
    };
  },
  created() {},
  methods: {
    // 关闭按钮的回调。仅当用户通过点击关闭图标或遮罩关闭 Dialog 时起效
    addDialogClose() {
      this.$confirm("此操作将导致文章信息丢失, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          // resetFields() 对整个表单进行重置，将所有字段值重置为初始值并移除校验结果
          this.$refs.addForm.resetFields();
          // this.$refs.addForm.validateField(['avatar']) // 图片需手动重置
          this.addForm.state = "";
          // this.addForm.cover_img = ""
          this.coverUrl = "";
          this.$emit("update:addDialogVisible", false);
        })
        .catch(() => {});
    },
    // 图片上传之前的回调
    beforeAvatarUpload(file) {
      console.log("beforeAvatarUpload", file);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    // 上传的方式
    httpRequest(obj) {
      console.log(obj);
      // obj.file获取File对象，而File对象又是继承自Blob。而Blob是最原始的文件对象
      // this.coverImgFile = obj.file;
      this.addForm.cover_img = obj.file;

      this.coverUrl = URL.createObjectURL(obj.file);
    },
    // 发布按钮/存为草稿回调事件
    addSubmit(state) {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          console.log("form", this.form);
          if (!this.addForm.content) {
            this.$message.error("请填写文章内容！");
          } else if (!this.coverUrl) {
            this.$message.error("请选择文章封面！");
          } else {
            this.addForm.state = state;
            // 后台需要FormData格式
            this.form = new FormData();
            // 文件对象
            // this.form.append("cover_img", this.coverImgFile);
            // 利用 form.append() 存储到 FormData 格式。这里存储格格式我用键值对
            // this.form.append("title", this.addForm.title);
            // this.form.append("cate_id", this.addForm.cate_id);
            // this.form.append("content", this.addForm.content);
            // this.form.append("state", state);
            // this.form.append("cover_img", this.addForm.cover_img);
            this.form.append({
              title: this.addForm.title,
              cate_id: this.addForm.cate_id,
              content: this.addForm.content,
              state: state,
              cover_img: this.addForm.cover_img,
            });
            const res = await addArticleApi(this.form);
            if (res.data.code === 0) {
              this.$refs.addForm.resetFields();
              this.addForm.state = "";
              this.coverUrl = "";
              // 更新页面数据
              this.$emit("updateData");
              this.$message.success("发表文章成功！");
            } else {
              this.$refs.addForm.resetFields();
              this.addForm.state = "";
              this.coverUrl = "";
              this.$message.error("发表文章失败！");
            }
            this.$emit("update:addDialogVisible", false);
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 取消
    cancel() {
      this.$emit("update:addDialogVisible", false);
    },
  },
};
</script>

<style lang="less" scoped>
.addDialog {
  // width: 100vw;
  height: 100vh;
  // height: 100%;
  font-size: 12px !important;

  ::v-deep .ql-editor {
    height: 300px;
  }

  .dialog-footer {
    display: flex;
    margin-left: 100px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-wrapper {
  // width: 350px;
  // height: 350px;
  .avatar {
    width: 400px;
    height: 280px;
    // display: block;
  }
}
.bottom {
  display: flex;
  margin-top: 10px;
}
.editor {
  // height: 300px;
}
</style>